package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;  //没事

    // 员工登录
    @Override
    public ResultInfo login(String username, String password) {
        // 根据username查询mapper(账号密码都能查到)
        Employee employee = employeeMapper.findByUsername(username);
        //判断能不能查到
        if (employee==null) {
            return ResultInfo.error("此用户名不存在");
        }
        // 将明文->md5加密
        String md5 = SecureUtil.md5(password);
        // 密码比较是否一致
        if (!StrUtil.equals(md5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        // 判断账号是否禁用
        if (employee.getStatus()==0) {
            return ResultInfo.error("此账号被禁用，请联系管理员");
        }
        //一致登录成功,返回结果
        return ResultInfo.success(employee);
    }



    // 查询员工列表
    @Override
    public List<Employee> findList(String name) {
        // 调用mapper查询
        return employeeMapper.findList(name);
    }


    //添加新员工
    @Override
    public void save(Employee employee) {
        //补全员工信息
        //使用雪花的id生成器
        long id = IdUtil.getSnowflake(1, 1).nextId();
        //补全员工id
        employee.setId(id);
        //给个员工初始密码// SecureUtil.md5("123456")
        String pwd = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(pwd);
        //设置0,1员工是否启用状态  Employee.STATUS_DISABLE==>常量
        employee.setStatus(Employee.STATUS_DISABLE);
     /*   //设置创建和更新时间
        employee.setCreateTime(new Date()); //todo 后期修改注释
        employee.setUpdateTime(new Date());
        //设置更新人(操作人)
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/
        //调用mapper添加
        employeeMapper.save(employee);

    }


    //编辑修改之前前 回显
    @Override
    public Employee findById(long id) {
        //调用mapper查询
        return employeeMapper.findById(id);
    }


    //修改
    @Override
    public void updateById(Employee employee) {
      //信息补全
    /*  //修改人
      employee.setUpdateUser(1L); // todo 暂时写死*/
      //修改时间
        employee.setUpdateTime(new Date());
        //调用mapper 把修改后的数据保存
        employeeMapper.updateById(employee);
    }


}
